﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace CSharpProj.MyExpression
{
    /// <summary>
    /// 一个可使用Lamdba表达式查询的数据库对象
    /// </summary>
    public class DbQuery<T> : IQueryable<T>
    {
        private readonly QueryProvider _provider;

        /// <summary>
        /// 创建一个可使用Linq集成查询的对象
        /// </summary>
        public DbQuery()
        {
            this.Expression = Expression.Constant(this);
        }

        IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            return ((IEnumerable<T>)Provider.Execute(this.Expression)).GetEnumerator();
        }

        public IEnumerator GetEnumerator()
        {
            return ((IEnumerable)Provider.Execute(this.Expression)).GetEnumerator();
        }

        public Expression Expression { get; set; }

        public Type ElementType { get { return typeof(T); } }

        public IQueryProvider Provider { get { return _provider; } }

        public override string ToString()
        {
            return _provider.Translate(this.Expression);
        }
    }
}
